<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .modal-backdrop {
            z-index: 1040 !important;
        }
        .modal-content {
            z-index: 1050 !important;
        }
        .btn-group-sm > .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .btn-action {
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="mb-0">用户管理</h2>
        </div>

        <!-- 用户表格 -->
        <div class="card">
            <div class="card-body">
                <table class="table table-bordered align-middle mb-0" id="userTable">
                    <thead class="table-light">
                        <tr>
                            <th style="width:60px;">#</th>
                            <th>用户名</th>
                            <th>角色</th>
                            <th style="width:250px;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- JS填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 用户详情模态框 (显示简介) -->
    <div class="modal fade" id="userDetailModal" tabindex="-1" aria-labelledby="userDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userDetailModalLabel">用户简介</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <img id="profileAvatar" src="" alt="用户头像" class="rounded-circle" style="width: 100px; height: 100px; object-fit: cover;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户ID</label>
                        <input type="text" class="form-control" id="detailUserId" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" id="detailUsername" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">昵称</label>
                        <input type="text" class="form-control" id="profileNickName" readonly>
                    </div>
                     <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="text" class="form-control" id="profileEmail" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">性别</label>
                        <input type="text" class="form-control" id="profileGender" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">个人简介</label>
                        <textarea class="form-control" id="profileBio" rows="3" readonly></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 (修改角色) -->
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">编辑用户角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" id="editUsername" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">角色</label>
                        <select class="form-select" id="editRole">
                            <option value="STUDENT">学生</option>
                            <option value="ADMIN">管理员</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveEditUserBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/jquery-3.7.1.min.js"></script>
<script>
    // 用户数据
    let users = [];
    let currentEditUser = null; // Store the user object being edited

    function renderTable() {
        const tbody = document.querySelector('#userTable tbody');
        tbody.innerHTML = '';
        users.forEach((user, idx) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.role}</td>
                <td>
                    <button class="btn btn-sm btn-info detail-btn btn-action me-2"><i class="fa fa-eye"></i> 详情</button>
                    <button class="btn btn-sm btn-warning edit-btn btn-action me-2"><i class="fa fa-pencil"></i> 编辑</button>
                    <button class="btn btn-sm btn-danger delete-btn btn-action"><i class="fa fa-trash"></i> 删除</button>
                </td>`;
            
            // 绑定详情事件
            $(tr).find('.detail-btn').click(function () {
                const userId = user.id;
                $.ajax({
                    url: `http://localhost:8082/api/user/profile/${userId}`,
                    method: 'GET',
                    success: function(data) {
                        if (data.code === 200) {
                            const profile = data.data;
                            // Populate detail modal with user and profile data
                            $('#detailUserId').val(user.id); // User ID from user list
                            $('#detailUsername').val(user.username); // Username from user list
                            $('#detailRole').val(user.role); // Role from user list
                            // Construct the full avatar URL, use default if avatarUrl is empty
                            const avatarFilename = profile && profile.avatarUrl ? profile.avatarUrl : '';
                            const fullAvatarUrl = avatarFilename ? `http://localhost:8082/upload/${avatarFilename}` : 'http://localhost:8082/upload/default.jpg'; // Use default avatar if filename is empty
                            $('#profileAvatar').attr('src', fullAvatarUrl); // Set the constructed URL
                            $('#profileNickName').val(profile ? profile.nickName : '');
                            $('#profileEmail').val(profile ? profile.email : '');
                            $('#profileGender').val(profile ? profile.gender : '');
                            $('#profileBio').val(profile ? profile.bio : '');
                            const modal = new bootstrap.Modal(document.getElementById('userDetailModal'));
                            modal.show();
                        } else {
                            alert('获取用户简介失败：' + (data.msg || '未知错误'));
                        }
                    },
                    error: function() {
                        alert('获取用户简介失败，无法连接到服务器');
                    }
                });
            });

            // 绑定编辑事件
            $(tr).find('.edit-btn').click(function () {
                currentEditUser = user; // Store the user object
                $('#editUsername').val(user.username);
                $('#editRole').val(user.role);
                const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                modal.show();
            });
            
            // 绑定删除事件
            $(tr).find('.delete-btn').click(function () {
                if (user.role === 'ADMIN') {
                    alert('您没有该权限！');
                    return;
                }
                if (confirm('确定要删除该用户吗？')) {
                    $.ajax({
                        url: `http://localhost:8082/api/user/${user.id}`,
                        method: 'DELETE',
                        success: function(data) {
                            if (data.code === 200) {
                                fetchUsers();
                                alert('删除成功！');
                            } else {
                                alert('删除失败：' + (data.msg || '未知错误'));
                            }
                        },
                        error: function() {
                            alert('删除失败，无法连接到服务器');
                        }
                    });
                }
            });
            tbody.appendChild(tr);
        });
    }

    // 获取用户数据
    function fetchUsers() {
        $.ajax({
            url: 'http://localhost:8082/api/users',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data.code === 200 && Array.isArray(data.data)) {
                    users = data.data;
                    renderTable();
                } else {
                    alert('获取用户数据失败');
                }
            },
            error: function() {
                alert('无法连接到用户接口');
            }
        });
    }

    // 保存编辑
    $('#saveEditUserBtn').click(function () {
        if (!currentEditUser) return; // Should not happen

        const userId = currentEditUser.id;
        const newRole = $('#editRole').val();
        
    

        $.ajax({
            url: `http://localhost:8082/api/user/${userId}/role?role=${newRole}`,
            method: 'PUT',
            success: function(data) {
                if (data.code === 200) {
                    fetchUsers(); // Refresh table after successful edit
                    // Update session storage if the edited user is the current logged-in user
                    const loggedInUserId = sessionStorage.getItem('userId');
                    if (loggedInUserId && parseInt(loggedInUserId) === currentEditUser.id) {
                        sessionStorage.setItem('userRole', newRole);
                    }
                    const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editUserModal'));
                    modal.hide();
                    alert('编辑成功！');
                } else {
                    alert('编辑失败：' + (data.msg || '未知错误'));
                }
            },
            error: function() {
                alert('编辑失败，无法连接到服务器');
            }
        });
    });

    // 初始化表格（页面加载时拉取数据）
    fetchUsers();
</script>
</body>
</html> 